package com.base.common.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.base.common.persistence.Dao;
import com.base.common.persistence.Model;
import com.base.common.persistence.Page;
import com.base.common.persistence.utils.SqlMapper;

/**
 * Service基类
 */
public abstract class CrudService<D extends Dao<T>, T extends Model<T>> {
	
	@Autowired
	SqlMapper sqlMapper;
	
	public SqlMapper getSqlMapper() {
		return sqlMapper;
	}
	
	@Autowired
	protected D dao;
	
	/**
	 * 获取单条数据
	 * @param id
	 * @return
	 */
	public T get(String id) {
		return dao.selectByPrimaryKey(id);
	}
	
	/**
	 * 获取单条数据
	 * @param entity
	 * @return
	 */
	public T get(T model) {
		return dao.selectByPrimaryKey(model.getPrimaryKeyValue());
	}
	
	/**
	 * 查询列表数据
	 * @param entity
	 * @return
	 */
	public List<T> findList(T model) {
		return dao.findList(model);
	}
	
	/**
	 * 删除数据
	 * @param entity
	 */
	public void delete(T model) {
		dao.deleteByPrimaryKey(model);
	}
	
	/**
	 * 查询分页数据
	 * @param page 分页对象
	 * @param entity
	 * @return
	 */
	public Page<T> findPage(Page<T> page, T entity) {
		entity.setPage(page);
		page.setList(dao.findAllList(entity));
		return page;
	}

	/**
	 * 保存数据（插入或更新）
	 * @param entity
	 */
	@Transactional(readOnly = false)
	public int saveOrUpdate(T entity) {
		int result = 0;
		if (entity.getIsNewRecord()){
			entity.preInsert();
			result = dao.insert(entity);
		}else{
			entity.preUpdate();
			result = dao.updateByPrimaryKey(entity);
		}
		
		return result;
	}
	
	@Transactional(readOnly = false)
	public int batchSave(List<T> list) {
		int result = 0;
		for (T entity : list) {
			entity.preInsert();
		}
		result = dao.batchInsert(list);
		
		return result;
	}
	
	@Transactional(readOnly = false)
	public int batchUpdate(List<T> list) {
		int result = 0;
		for (T entity : list) {
			entity.preUpdate();
		}
		result = dao.batchUpdate(list);
		
		return result;
	}
	
	
	public Page getPage(Page page, String sql, Class<T> a, Map<String, String> params) {
		int pageNo = page.getPageNo();
		int pageSize = page.getPageSize();
		int startIndex = (pageNo - 1) * pageSize;
		//int endIndex = pageNo * pageSize - 1;
		page.setRecords(this.getSqlMapper().selectList(sql, params).size());
		sql += " LIMIT " + startIndex + "," + pageSize;
		List<T> list = this.getSqlMapper().selectList(sql, params, a);
		page.setRows(list);
		return page;
	}
	
	
	public List<T> getList(String sql, Class<T> a, Map<String, String> params) {
		List<T> list = this.getSqlMapper().selectList(sql, params, a);
		return list;
	}
	
	public T getOne(String sql, Class<T> a, Map<String, String> params) {
		T t = this.getSqlMapper().selectOne(sql, params, a);
		return t;
	}
	
	public int delete(String sql) {
		return this.getSqlMapper().delete(sql);
	}
}
